/*
 * Copyright (c) 2006-2021, RT-Thread Development Team
 *
 * SPDX-License-Identifier: Apache-2.0
 *
 * Change Logs:
 * Date           Author       Notes
 * 2024-05-25     liuchao       the first version
 */
#define LOG_TAG "sleep"
#include <ulog.h>
#include "configuration.h"
#include <drv_btn.h>
#include <time.h>
#include <drv_pmhw.h>
#include <drv_sensor.h>
#include <drv_relay.h>
#include <drv_ec.h>
#include "aliyun.h"
#include "app_net.h"
#include "wdt.h"
#include "led_beep.h"
#include "rotate.h"
#include <drv_btn.h>

void rt_pm_dump_status();

int sleep_seconds(rt_int32_t sleep_time)
{
    //time_t now;

    HAL_PWR_EnableWakeUpPin(PWR_WAKEUP_PIN1);
    stm32_pmtim_start(sleep_time);

    //now = time(RT_NULL);    // 获取当前的系统时间
    //rt_kprintf("%.*s", 25, ctime(&now));    // 打印系统时间

    return 0;
}

void standby_seconds(rt_int32_t seconds)
{
    if (seconds <= 0)
    {
        sleep_seconds_set(0);
        LOG_E("Invalid standby seconds %ld", seconds);
        return;
    }
    rt_uint32_t saved_seconds = sleep_seconds_get();

    if (saved_seconds > 0)
    {
        LOG_I("standby %d", seconds);
        sleep_seconds_set(0);

        sleep_seconds(seconds);  // 设置 RTC wakeup 时间

        rt_pm_request(PM_SLEEP_MODE_STANDBY);
        rt_pm_dump_status();
        rt_pm_module_get_status();

        rt_pm_release(PM_SLEEP_MODE_NONE);
        rt_pm_dump_status();
    }
    else
    {
        sleep_seconds_set(seconds);
        rt_hw_cpu_reset();
    }
}

static rt_tick_t s_net_up_ts = 0;
static int s_publishing = 0;
int publishing()
{
    return s_publishing;
}
static void pub_entry(void* arg)
{
    while (1)
    {
        rt_thread_mdelay(1000);
        if (is_ethernet_up(0))
        {
            s_net_up_ts = rt_tick_get_millisecond();    //网络正常，记录时刻s_net_up_ts
        }
        else
        {                                                               //网络异常
            led_beep(PANEL_LED_RED, LED_NOTIFY_MODE_ALARM_NET_DOWN);    //LED闪2下
            // led_beep(PANEL_BEE, LED_NOTIFY_MODE_ALARM_NET_DOWN);
            if ((rt_tick_get_millisecond() - s_net_up_ts) > (300 * 1000))   //如果断网300秒，切断4G模块电源，
            {
                ec_disable();                   //关闭4G模块电源
                relay_off(RELAY_PERIPH_PWR);    //关闭继电器
                rt_thread_mdelay(10000);        //延时10秒钟
                standby_seconds(5);             //重启
            }
            continue;
        }

        rt_int32_t update_interval = auto_mode_update_inverval();
        rt_int32_t update_delay = auto_mode_update_delay();

        if (update_interval <= 0 || update_delay < 0)
        {
            continue;
        }

        struct timeval tv = { 0 };
        struct timezone tz = { 0 };

        gettimeofday(&tv, &tz);
        if (tv.tv_sec < 1716479260)
        {
            continue;
        }

        time_t now = time(RT_NULL);
        struct tm* now_local = localtime(&now);
        int seconds_elapsed = (now_local->tm_hour * 3600) + (now_local->tm_min * 60) + now_local->tm_sec;
        //rt_int32_t s = update_interval + update_delay - (seconds_elapsed % update_interval);
        if( update_interval <=0 ) update_interval=3;
        rt_int32_t s = (seconds_elapsed - update_delay) % update_interval;
        if (s == 0)             //到上报数据的时间了
        {
            int auto_mode = btn_state(BTN_AUTO);   //开关在自动位置
            int pause_switch = pause_switch_get();  //暂停状态
            s_publishing = 1;
            relay_on(RELAY_PERIPH_PWR);             //打开继电器
            if (auto_mode && pause_switch && update_interval > AUTO_MODE_UPDATE_INTERVAL_THD)
            {                                       //在自动状态&& 暂停 && 时间间隔>120秒
                rt_thread_mdelay(10000);            //打开继电器预热10秒钟
            }
            app_pub_running_properties();           //上报数据
            if (auto_mode && pause_switch && update_interval > AUTO_MODE_UPDATE_INTERVAL_THD)
            {                                       //在自动状态&& 暂停 && 时间间隔>120秒
                while (rotating())                  //等待油缸不动作
                {
                    rt_thread_mdelay(10);
                }
                relay_off(RELAY_PERIPH_PWR);        //关闭继电器
                s_publishing = 0;
            }
        }
    }
}

static int app_sleep_init()
{
    ulog_tag_lvl_filter_set(LOG_TAG, LOG_LVL_INFO);
    s_net_up_ts = rt_tick_get_millisecond();

    rt_thread_t t = rt_thread_create("pub", pub_entry, NULL, 2048, 20, 1000);
    rt_thread_startup(t);
    return RT_EOK;
}
INIT_APP_EXPORT(app_sleep_init);
